// pages/index/index.js
var utils = require('../../utils/util');
var initApp = require('../../utils/initlogin');

Page({
  gotoPage: utils.gotoPage,
  initAppUser: initApp.initAppUser,

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userInfo: '1',
    productList: []
  },

  // 授权按钮点击
  getUserInfo: function(e) {
    console.log('userInfo:', e.detail.userInfo)
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      console.log('用户按了允许授权按钮');
      wx.setStorageSync('userInfo', e.detail.userInfo);
      this.setData({
        userInfo: e.detail.userInfo
      });
      wx.showTabBar({});
    } else {
      //用户按了拒绝按钮
      console.log('用户按了拒绝按钮');
      this.setData({
        userInfo: ''
      });
      wx.clearStorage();
      wx.hideTabBar({});
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var HOST = getApp().globalData.HOST;
    var openid = wx.getStorageSync('openid');
    console.log('HOST:', HOST)

    // 初始化用户信息
    that.initAppUser();

    // 获取商品列表
    that.getProductsList();
  },

  // 获取商品列表
  getProductsList: function() {
    var that = this;
    var HOST = getApp().globalData.HOST;

    wx.request({
      url: HOST + 'product',
      data: {
        ACTION: 'QUERY'
      },
      success(resp) {
        console.log('product:', resp);
        for (var i = 0; i < resp.data.data.length; i++) {
          var p = resp.data.data[i];
          p.covers = p.covers.split(', ');
        }
        var productList = resp.data.data;
        that.setData({
          productList: productList
        });
        wx.setStorage({
          key: 'productList',
          data: productList,
        });
      },
    });
  },

  // 点击购买
  buyNow: function(event) {
    var pid = getCurrentPages()[0].data.pid;
    // var pid = event.currentTarget.dataset.pid;
    wx.navigateTo({
      url: '/pages/buy/buy?pid=' + pid,
    })
  },

  // 进入详情页
  gotoDetail: function(event) {
    var pid = event.currentTarget.dataset.pid;
    wx.navigateTo({
      url: '/pages/home/home?pid=' + pid,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '国学小书童',
      path: '/pages/index/index',
      imageUrl: '/images/g1.jpg',
    }
  },
})